/*
 * @Author: Wilbur
 * @Date: 2018-11-18 16:46:28
 * @Last Modified by: Wilbur
 * @Last Modified time: 2018-12-08 14:31:25
 */
<template>
    <div class="container lottery-list-container">
        <div class="operation-wrapper">
            <el-button
                @click="handleRoute('LotteryEdit')"
                type="primary"
                :disabled="!authResult.auth_edit"
                size="small">新增抽奖</el-button>
        </div>
        <div class="content-wrapper">
            <div class="table-wrapper">
                <el-table
                    :data="tableData"
                    style="width: 100%;"
                >
                    <el-table-column
                        fixed="left"
                        header-align="left"
                        align="center"
                        :width="50"
                        label="序号">
                        <template slot-scope="scope">
                            <div class="table-index">
                                {{ scope.$index + 1 }}
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column
                        fixed="left"
                        prop="title"
                        show-overflow-tooltip
                        width="300px"
                        label="活动名称" />
                    <el-table-column
                        :formatter="limitFormatter"
                        prop="try_limit"
                        width="100px"
                        show-overflow-tooltip
                        label="参与限制" />
                    <el-table-column
                        width="300px"
                        :formatter="timeFormatter"
                        prop="start_time"
                        show-overflow-tooltip
                        label="有效期" />
                    <el-table-column
                        :formatter="emptyFormatter"
                        prop="lottery_item_list"
                        show-overflow-tooltip
                        label="活动奖品">
                        <template slot-scope="scope">
                            <div>
                                <template v-if="scope.row.lottery_item_list.length <= 0">--</template>
                                <template v-else>
                                    <div
                                        class="lottery-item"
                                        v-for="(lotteryItem, lotteryIndex) in scope.row.lottery_item_list"
                                        :key="lotteryIndex">{{ lotteryItem.title }}</div>
                                </template>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column
                        :formatter="statisticFormatter"
                        prop="statistic"
                        show-overflow-tooltip
                        label="参与人/次" />
                    <el-table-column
                        :formatter="awardFormatter"
                        prop="statistic"
                        show-overflow-tooltip
                        label="领到/未领到人" />
                    <el-table-column
                        prop="date"
                        label="操作"
                        width="150"
                        fixed="right">
                        <template slot-scope="scope">
                            <div>
                                <el-popover
                                    placement="top"
                                    width="200"
                                    popper-class="lottery-list-preview-popover"
                                    trigger="click">
                                    <el-button
                                        slot="reference"
                                        type="text">预览</el-button>
                                    <img
                                        :src="`${baseUrl}/__local/common%5Cqrcode?content=${escape(mobileUrl + '/lottery?lottery_no=' + scope.row.lottery_no)}&__ticket=${sessionTicket}`"
                                        alt=""
                                        width="104px"
                                        height="104px">
                                </el-popover>
                                <el-button
                                    type="text"
                                    @click="fnShowLotteryLink(scope.row.lottery_no)">链接</el-button>
                                <el-button
                                    type="text"
                                    :disabled="!authResult.auth_edit"
                                    @click="handleRoute('LotteryEdit',{lottery_no: scope.row.lottery_no})">编辑</el-button>
                            </div>
                            <div>
                                <el-button
                                    type="text"
                                    :disabled="!authResult.auth_record_list"
                                    @click="handleRoute('LotteryRecord', {
                                        lottery_no: scope.row.lottery_no
                                })">抽奖记录</el-button>
                                <el-button
                                    type="text"
                                    :disabled="!authResult.auth_delete"
                                    class="btn-delete"
                                    @click="fnConfimDel(scope.row.lottery_no)">删除</el-button>

                            </div>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </div>
        <!-- 抽奖链接 -->
        <el-dialog
            title="复制链接"
            :visible.sync="dialogLinkVisible"
            width="30%"
            @close="targetLink = ''">
            <div class="dialog-link">
                <span class="link-label">原链接:</span>
                <span
                    class="link-value"
                    @click="fnChooseText('link')"
                    ref="link">{{ targetLink }}</span>
            </div>
            <div class="dialog-link">
                <span class="link-label">短链接:</span>
                <span
                    class="short-link-value"
                    @click="fnChooseText('shortLink')"
                    ref="shortLink">{{ shortLink }}</span>
            </div>

            <span
                slot="footer"
                class="dialog-footer" />
        </el-dialog>

        <!-- 分页 -->
        <div
            class="pagination-wrapper clearfix"
            v-if="tableData.length > 0"
        >
            <el-pagination
                background
                layout="total, prev, pager, next"
                :current-page.sync="page.now_page"
                :total="page.total_count"
                :page-size="page.page_size"
                @current-change="getTableData"
            />
        </div>
        <!-- /分页 -->
    </div>
</template>

<script>
let sortMap = {
    'ascending': 'asc',
    'descending': 'desc'
};

import { dateFormat } from '@/assets/js/utils';

export default {
    data() {
        return {
            showQrDialog: false,
            showLinkDialog: false,
            authResult: {},
            tableData: [],
            page: {
                now_page: 1,
                total_count: 0,
                page_size: 0
            },

            targetLink: '',//链接
            shortLink: '', //短链接
            dialogLinkVisible: false,
            baseUrl: '',
            mobileUrl: '',
            escape: escape,
            sessionTicket: localStorage.getItem('sessionTicket')
        };
    },
    created() {
        this.authResult = this.$route.meta.authResult;
        this.$store.commit('SET_HEADER', [
            {
                title: "任务反馈系统",
            },
            {
                title: "抽奖活动"
            }
        ]);
        this.baseUrl = this.$baseUrl;
        this.mobileUrl = location.host == 'phaadmin.wxhand.com' ? 'http://class.zsdx.cn' : 'http://task.wxhand.com';
        this.getTableData();
    },
    methods: {
        fnShowLotteryLink(lottery_no) {
            this.targetLink = `${this.mobileUrl}/lottery?lottery_no=${lottery_no}`;
            this.$post('/__local/common%5Cshort_url', {
                url: this.targetLink
            }, resp => {
                if (resp.code == 1) {
                    this.shortLink = resp.data.short_url;
                } else {
                    this.shortLink = '--';
                }
                this.dialogLinkVisible = true;
            });
        },
        /**
         * 弹出确认删除弹窗
         */
        fnConfimDel(lottery_no) {
            this.$confirm('此操作将删除该活动, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$post('/task/lottery%5Cdelete', {
                    lottery_no:lottery_no
                }, resp =>{
                    if(resp.code == 1){
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                        this.getTableData();
                    }else{
                        this.$message({
                            type: 'warning',
                            message: '删除成功!'
                        });
                    }
                });
            }).catch(() => {
                console.log('cancel');
            });
        },
        /**
         * 跳转页面
         */
        handleRoute(name, query) {
            let obj = {
                name
            };

            if (query) {
                obj.query = query;
            }

            this.$router.push(obj);
        },

        /**
         * 获取表格数据
         */
        getTableData(page) {
            this.$post('/task/lottery%5Clist', {
                page_id: page || this.page.now_page,
            }, resp => {
                if (resp.code == 1) {
                    this.tableData = resp.data.list;
                    this.page.now_page = resp.data.page.now_page;
                    this.page.total_count = resp.data.page.total_count;
                    this.page.page_size = resp.data.page.page_size;
                } else {
                    this.$message({
                        type: 'warngin',
                        ceter: true,
                        message: resp.msg
                    });
                }
            });
        },

        fnChooseText(name) {
            let text = this.$refs[name];
            let range = '';

            if (document.body.createTextRange) {
                range = document.body.createTextRange();

                range.moveToElementText(text);
                range.select();
            } else if (window.getSelection) {
                var selection = window.getSelection();

                range = document.createRange();

                range.selectNodeContents(text);
                selection.removeAllRanges();
                selection.addRange(range);

            } else {
                alert("none");
            }
        },

        /**
         * 列表渲染辅助函数：列表项为空处理
         */
        emptyFormatter(row, column, val) {
            if (!val) {
                return '--';
            }
            return val;
        },
        timeFormatter(row, column, val) {
            let start = dateFormat(row.start_time * 1000, 'yyyy-MM-dd HH:mm:ss');
            let end = dateFormat(row.end_time * 1000, 'yyyy-MM-dd HH:mm:ss');

            return start + '~' + end;
        },
        limitFormatter(row, column, val) {
            if (!val && val !== 0) {
                return '--';
            } else if (val == 0) {
                return '不限';
            } else if (val == 1) {
                return '一人一次';
            }
            return val;
        },
        statisticFormatter(row, column, val) {
            if (!val) {
                return '--';
            }
            return val.try_user_count + '/' + val.try_count;
        },
        awardFormatter(row, column, val) {
            if (!val) {
                return '--';
            }
            return val.award_user_count + '/' + val.not_award_user_count;
        },
    }
};
</script>

<style lang="less" scoped>
    .container {
      display: flex;
      flex-direction: column;
      width: 100%;
        padding: 15px !important;
    }
    .operation-wrapper {
      display: flex;
      flex-direction: row-reverse;
      padding: 12px 23px;
      background-color: #fff;

      .el-button {
        margin-left: 10px;
      }
    }
    .content-wrapper {
      flex: 1;
      display: flex;
      flex-direction: column;
      margin: 15px;
      overflow: hidden;
    }
    .search-wrapper {
      padding: 15px;
      background-color: #fff;
    }
    .filter-item {
      margin-bottom: 15px;
      .el-form-item {
        margin-bottom: 0;
      }
      .el-autocomplete {
        width: 100%;
      }
    }
    .table-wrapper {
      flex: 1;
      background-color: #fff;

      .el-button {
        padding: 0;
        margin-left: 10px;
      }

      .btn-delete {
        color: #fd4d32;
        &.is-disabled {
          color: #c0c4cc;
          cursor: not-allowed;
        }
      }
    }
    .pagination-wrapper {
      padding-top: 10px;
      .el-pagination {
        float: right;
        padding: 0;
        background-color: transparent;
      }
    }
    .qr-dialog-wrap {
      text-align: center;
    }
    .dialog-link {
      & + .dialog-link {
        margin-top: 20px;
      }
      .link-label {
        font-weight: 500;
        margin-right: 20px;
      }
    }
    .btn-delete {
      color: #fd4d32;
      &.is-disabled {
        color: #c0c4cc;
        cursor: not-allowed;
      }
    }
</style>
<style lang="less">
    .lottery-list-preview-popover {
      min-width: auto !important;
      width: 120px !important;
      height: 120px;
      padding: 8px !important;
    }
</style>
